package com.sinosun.autotestmachine;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

public class FileAdapter extends BaseAdapter {
	
	private List<FileElement> content = new ArrayList<FileElement>();
	private Context context;
	private OnFileItemClickListener listener;
	
	public FileAdapter(Context context, List<FileElement> content) {
		this.context = context;
		this.content = content;
	}

	@Override public int getCount() {
		if (content == null) {
			return 0;
		} return content.size();
	}

	@Override public Object getItem(int position) {
		return content.get(position);
	}

	@Override public long getItemId(int position) {
		return position;
	}

	@Override public View getView(final int position, View convertView, ViewGroup parent) {
		Holder holder;
		if (convertView == null) {
			holder = new Holder();
			convertView = LayoutInflater.from(context).inflate(R.layout.file_item_layout, null);
			holder.check = (CheckBox) convertView.findViewById(R.id.check);
			holder.fileName = (TextView) convertView.findViewById(R.id.file);
			convertView.setTag(holder);
		} else {
			holder = (Holder) convertView.getTag();
		}
		
		if (content.get(position).getChecked()) {
			holder.check.setChecked(true);
		} else {
			holder.check.setChecked(false);
		}
		holder.check.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				listener.onItemChecked(position);
			}
		});
		
		String show = new String();
		if (!content.get(position).IsFile()) {
			show = show + "(D)";
		}
		show = show + content.get(position).getFileName();
		holder.fileName.setText(show);
		holder.fileName.setOnClickListener(new OnClickListener() {
			@Override public void onClick(View v) {
				listener.onItemClicked(position);
			}
		});
		return convertView;
	}
	
	class Holder {
		CheckBox check;
		TextView fileName;
	}
	
	public void setOnFileItemClickListener(OnFileItemClickListener listener) {
		this.listener = listener;
	}

}
